import { s_freezeShipping, s_getSelectData, s_getShippingInfo, s_getTableInfo, s_operateInfo, s_saveShippingInfo, s_updateInfo, status2text } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useModel } from "@umijs/max";
import { Button, Card, message, Modal, Space, Table, TableColumnProps, Tag, Typography } from "antd";
import moment from "moment";
import React, { useRef, useState } from "react";

const App:React.FC=()=>{
    const [selectedRows,setSelectedRows]=useState<DataType[]>([]);
    const [selectedRowKeys,setSelectedRowKeys]=useState<React.Key[]>([]);
    const [open,setOpen]=useState(false);
    const [etype,setEtype]=useState(0);

    const table_ref=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();
    const {initialState, setInitialState } = useModel('@@initialState');
    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

    interface DataType{
        x_id:number,
        id:number,
        code:string,
        name:string,
        ename:string,
        operate_time:string,
        operater_id:string,
        status:number,
    }
    const columns:ProColumns<DataType>[]=[
        {dataIndex:'x_id',hidden:true},
        {key:'id',dataIndex:'id',title:'ID'},
        {dataIndex:'code',title:'单位编码'},
        {dataIndex:'name',title:'单位名称'},
        {dataIndex:'ename',title:'英文名称'},
        {dataIndex:'operate_time',title:'修改时间',
            render:(text)=>moment(moment(text?.toString()).toDate()).format('YYYY-MM-DD')},
        {dataIndex:'operater_name',title:'修改人'},
        {dataIndex:'status',title:'状态',
            render:(text:any)=><Tag style={{width:60}} color={text==2?'blue':text==3?'red':''}>{status2text(text)}</Tag>},
    ];
     
    async function add(){
        setSelectedRowKeys([]);
        setEtype(1);
        setOpen(true);
    }
    async function edit(){
        if(selectedRowKeys.length==0)
            message.warning('请先选择要编辑的行。');
        else if(selectedRows[0].status==2||selectedRows[0].status==3)
            message.warning('已关闭、删除的档案不能编辑。请先进行恢复。');
        else{
            setEtype(0);
            setOpen(true);
        }
    }
    async function save(){
        setOpen(false);
        setSelectedRowKeys([]);
        const fdata2=form_ref.current?.getFieldsValue();
        const fdata={...fdata2,
            operate_time:moment(moment(fdata2.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
        }
        //source,x_id,operater_id,etype,fdata  通用的表格保存
        const x=await s_updateInfo({source:'unit',x_id:1,
                     operater_id:initialState?.currentUser?.userid,etype,fdata});
        if(x.success){
            message.success('数据保存成功。');
            setOpen(false);
            setEtype(1);
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('数据保存失败，请检查。');
    }

    async function operate(otype:number){
        const id=selectedRows[0].id;
        //s_operateInfo({source:'base_ware',operater_id:1,type:tabKey,otype,id})通用表格操作冻结删除
        const x=await s_operateInfo({source:'base_unit',x_id:1,
               operater_id:initialState?.currentUser?.userid,otype,id});

        if(x.success){
            message.success('更新成功。');
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('更新失败，请联系管理员。');
    }
    

    return (
        <>
        <ProCard title='计量单位管理' style={{height:'75vh',overflow:'auto'}} 
        extra={<Space>
            <Button onClick={()=>add()}>新增</Button>
            <Button onClick={()=>edit()}>编辑</Button>
            
            <Button onClick={()=>operate(2)}>关闭</Button>
            <Button onClick={()=>operate(3)}>删除</Button>
            <Button onClick={()=>operate(1)}>恢复</Button>
            </Space>}>
            {/* {JSON.stringify(selectedRows)} */}
            <ProTable<DataType> 
            actionRef={table_ref}
            search={false} 
            columns={columns}
            rowKey='id'
            rowSelection={{
                type:'radio',
                selectedRowKeys:selectedLineKeys,
                onChange:(selectedRowKeys,selectedRows)=>{
                    setSelectedRows(selectedRows);
                    setSelectedRowKeys(selectedRowKeys);
                    setSelectedLineKeys(selectedRowKeys);
                },
            }}
          onRow={(record)=>{
             return {
               onClick:()=>{
                const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedRowKeys([k]);
                     setSelectedRows([record]);
                     setSelectedLineKeys([k]);
              },
            }
           }}
            request={async (params)=>{
                var id=0;
                if(selectedRowKeys.length!=0)
                    id=Number.parseInt(selectedRowKeys[0].toString());
                const x=await s_getTableInfo({source:'v_unit',x_id:1,id:id});  //通用的表格取数函数
                return{
                    data:x.data,
                    success:true,
                }
            }}
            scroll={{
                y:'55vh',
            }}
           options={false}
        
        />
        <Modal title={etype==0?'编辑计量单位':'新增计量单位'} destroyOnClose closable onCancel={()=>setOpen(false)}
            open={open} onOk={()=>form_ref.current?.submit()}
        >
             <ProForm submitter={false} formRef={form_ref} 
               onFinish={()=>save()}
               initialValues={etype==1?{
                       operate_time:moment().format('YYYY-MM-DD'),
                       operater_id:initialState?.currentUser?.userid,
                       status:1,
                   }:{
                      ...selectedRows[0],
                      operate_time:moment(moment(selectedRows[0]?.operate_time).toDate()).format('YYYY-MM-DD'),
                 }}
             >
                <ProFormText name='x_id' hidden/>
                <ProFormText name='id' hidden/>
                <ProFormText name='code' label='单位编码' rules={[{required:true,message:'必输项'}]}/>
                <ProFormText name='name' label='单位名称' rules={[{required:true,message:'必输项'}]}/>
                <ProFormText name='ename' label='英文名称' rules={[{required:true,message:'必输项'}]}/>
                <ProFormRadio.Group name='status' label='状态'
                   options={[{label:'正常',value:1},{label:'关闭',value:2,style:{color:'blue'}},
                             {label:'删除',value:3,style:{color:'red'}}]}
                />
                <ProFormDatePicker name='operate_time' label='操作时间'/>
                <ProFormSelect name='operater_id' label='操作人'
                     showSearch
                        request={async ()=>{
                            const x=await s_getSelectData({x_id:1,source:'base_person'});
                         return x.data;}}
                />
             </ProForm>
        </Modal>
        </ProCard>
        </>
    );
}

export default App;